import html2canvas from 'html2canvas'
import moment from 'moment'

function captureDom(domContainer, prefix) {
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  canvas.width = domContainer.clientWidth
  canvas.height = domContainer.clientHeight
  html2canvas(domContainer).then(function (canvas) {
    ctx.drawImage(canvas, 0, 0)
    const base64Data = canvas.toDataURL('image/png')
    download(prefix + moment().format('YYYY-MM-DD_HHmmss') + '.png', base64Data)
  })
}

function download(filename, base64Data) {
  const aLink = document.createElement('a');
  const blob = base64ToBlob(base64Data);
  const ev = document.createEvent('HTMLEvents');
  ev.initEvent('click', true, true);
  aLink.download = filename;
  aLink.href = URL.createObjectURL(blob);
  aLink.click();
}

function base64ToBlob(code) {
  const parts = code.split(';base64,')
  const contentType = parts[0].split(':')[1]
  const raw = window.atob(parts[1])
  const rawLength = raw.length
  const uInt8Array = new Uint8Array(rawLength)
  for (let i = 0; i < rawLength; ++i)
    uInt8Array[i] = raw.charCodeAt(i)
  return new Blob([uInt8Array], { type: contentType })
}
captureDom(dom,'保存的文件名字')
export { captureDom }